<template>
	<view class="container">
		<!-- 当前车辆 -->
		<view class="car-container" @click="carMenuShow = true">
			<!-- 左侧车辆信息 -->
			<view class="car-info-left">
				<up-icon name="arrow-down" class="arrow-icon"></up-icon>
				<text class="car-name">{{ currentCar?.name }}</text>
			</view>
			<!-- 右侧油价信息 -->
			<view class="oil-info-right" v-if="oilPriceInfo && oilPriceInfo.oilPrices">
				<text class="oil-price">92# {{ oilPriceInfo.oilPrices || '0.00' }}元</text>
				<text class="update-date">下次调价 {{ oilPriceInfo.nextUpdate || '暂无数据' }}</text>
			</view>
		</view>

		<!-- 车辆切换菜单 -->
		<up-action-sheet :actions="carMenuList" :title="'选择车辆'" :cancel-text="'取消'" :show="carMenuShow" @select="carSelect"
			@close="carMenuShow = false" round="12rpx">
		</up-action-sheet>

		<!-- 用车统计 -->
		<view class="fuel-module-container">
			<view class="fuel-module-header">
				<text class="fuel-module-title">📊 用车统计</text>
				<text class="total-costs">总费用: {{ totalCosts.toFixed(2) }} 元</text>
				<view class="year-picker-wrapper" @tap="openYearPicker('fuelModule')">
					<text>{{ yearSelection.fuelModule === '全部' ? '全部' : yearSelection.fuelModule + ' 年' }}</text>
				</view>
			</view>
			<up-picker :show="yearPickerShow.fuelModule" :columns="yearColumnsData" closeOnClickOverlay
				@confirm="(e) => handleYearConfirm(e, 'fuelModule')" @cancel="() => handleYearCancel('fuelModule')"
				@close="() => handleYearCancel('fuelModule')">
			</up-picker>
			<view class="fuel-grid">
				<view class="fuel-card">
					<text class="fuel-title">综合油耗</text>
					<text class="fuel-value">{{ fuelData.fuelTotalFuelEconomy }}</text>
					<text class="fuel-unit">升/百公里</text>
				</view>
				<view class="fuel-card">
					<text class="fuel-title">油费成本</text>
					<text class="fuel-value">{{ fuelData.fuelTotalCostPerKm }}</text>
					<text class="fuel-unit">元/公里</text>
				</view>
				<view class="fuel-card">
					<text class="fuel-title">总加油量</text>
					<text class="fuel-value">{{ fuelData.fuelTotalLiters }}</text>
					<text class="fuel-unit">升</text>
				</view>
				<view class="fuel-card">
					<text class="fuel-title">总里程</text>
					<text class="fuel-value">{{ fuelData.fuelTotalMileage }}</text>
					<text class="fuel-unit">公里</text>
				</view>
				<view class="fuel-card">
					<text class="fuel-title">总油费</text>
					<text class="fuel-value">{{ fuelData.fuelTotalCosts }}</text>
					<text class="fuel-unit">元</text>
				</view>
				<view class="fuel-card">
					<text class="fuel-title">总养车费用</text>
					<text class="fuel-value">{{ fuelData.expenseTotalCosts }}</text>
					<text class="fuel-unit">元</text>
				</view>
			</view>
		</view>

		<!-- 油耗趋势 -->
		<view class="trend-module-container">
			<view class="trend-module-header">
				<text class="trend-module-title">📈 油耗趋势</text>
				<view class="year-picker-wrapper" @tap="openYearPicker('trendModule')">
					<text>{{ yearSelection.trendModule === '全部' ? '全部' : yearSelection.trendModule + ' 年' }}</text>
				</view>
				<up-picker :show="yearPickerShow.trendModule" :columns="yearColumnsData" closeOnClickOverlay
					@confirm="(e) => handleYearConfirm(e, 'trendModule')" @cancel="() => handleYearCancel('trendModule')"
					@close="() => handleYearCancel('trendModule')">
				</up-picker>
			</view>
			<qiun-data-charts v-if="trendData.length > 0" type="line" :opts="chartOpts" :chartData="chartData"
				style="width: 100%; height: 300px;" />
			<up-empty v-else text="暂无油耗数据" mode="data" style="height: 300px;">
			</up-empty>
		</view>

		<!-- 养车分类数据分布 -->
		<view class="expense-module-container">
			<view class="expense-module-header">
				<text class="expense-module-title">💰 养车费用</text>
				<view class="year-picker-wrapper" @tap="openYearPicker('expenseModule')">
					<text>{{ yearSelection.expenseModule === '全部' ? '全部' : yearSelection.expenseModule + ' 年' }}</text>
				</view>
				<up-picker :show="yearPickerShow.expenseModule" :columns="yearColumnsData" closeOnClickOverlay
					@confirm="(e) => handleYearConfirm(e, 'expenseModule')" @cancel="() => handleYearCancel('expenseModule')"
					@close="() => handleYearCancel('expenseModule')">
				</up-picker>
			</view>
			<qiun-data-charts v-if="expenseData.length > 0" type="pie" :opts="pieChartOpts" :chartData="pieChartData"
				style="width: 100%; height: 300px;" />
			<up-empty v-else text="暂无养车数据" mode="data" style="height: 300px;">
			</up-empty>
		</view>

		<!-- 底部浮动按钮（添加加油、养车记录） -->
		<up-float-button :isMenu="true" :list="floatButtonList" @item-click="floatButtonClick" bottom="100px"
			backgroundColor="#4096FF" color="#FFFFFF">
		</up-float-button>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import * as homeApi from '../../api/home'
import * as carApi from '../../api/car'
import { getCurrentOilPriceWithNextUpdate } from '../../utils/oilPrice'

// ======= 状态管理 =======
const carList = ref([]) 							// 车辆列表数据
const carMenuShow = ref(false) 				// 车辆选择菜单显示状态
const currentCar = ref({ 							// 当前选中的车辆信息
	id: null,
	name: ''
})

// 当前油价信息
const oilPriceInfo = ref({
	oilPrices: 0.00,
	nextUpdate: 'YYYY-MM-DD'
})

// 用车统计数据
const fuelData = ref({
	fuelTotalFuelEconomy: 0, 						// 综合油耗
	fuelTotalCostPerKm: 0, 							// 油费成本
	fuelTotalLiters: 0, 								// 总加油量
	fuelTotalMileage: 0, 								// 总里程
	fuelTotalCosts: 0, 									// 总油费
	expenseTotalCosts: 0 								// 总养车费用
})

// 油耗趋势数据
const trendData = ref([])

// 养车分类数据
const expenseData = ref([])

const yearColumnsData = ref([])				// 年份筛选器列数据
const yearSelection = ref({  					// 年份筛选器选中的年份（用车数据、趋势数据）
	fuelModule: '全部',
	trendModule: '全部',
	expenseModule: '全部'
})
const yearPickerShow = ref({ 					// 年份筛选器显示状态（用车数据、趋势数据）
	fuelModule: false,
	trendModule: false,
	expenseModule: false
})

// 悬浮按钮菜单（加油、养车）
const floatButtonList = ref([
	{
		key: '加油',
		name: '加油',
		color: '#FA8C16',
		backgroundColor: '#FFF7E6'
	},
	{
		key: '养车',
		name: '养车',
		color: '#52C41A',
		backgroundColor: '#F6FFED'
	},
])

// 油耗趋势 -> 图表配置
const chartOpts = ref({
	color: ['#1890ff'],
	padding: [30, 20, 20, 10],
	dataLabel: false,
	dataPointShape: false,
	enableScroll: false,
	legend: {
		show: false,
	},
	xAxis: {
		disabled: false,
		disableGrid: true,
		labelCount: 4,
		axisLine: {
			lineStyle: {
				color: '#eee'
			}
		},
		splitLine: {
			show: false
		}
	},
	yAxis: {
		disabled: false,
		gridType: 'dash',
		splitLine: {
			lineStyle: {
				color: '#eee'
			}
		}
	},
	extra: {
		line: {
			type: 'curve',
			width: 2,
			dot: {
				size: 6,
				active: {
					r: 8
				}
			}
		}
	}
})

// 养车分类数据饼图 -> 图表配置
const pieChartOpts = ref({
	color: ['#1890ff', '#52c41a', '#fa8c16', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#faad14'],
	padding: [10, 10, 10, 10],
	dataLabel: true,
	radius: [40, 120],
	legend: {
		show: true,
		opacity: 0.8,
		itemGap: 10,
		itemWidth: 15,
		itemHeight: 15,
		direction: 'horizontal',
		position: 'bottom'
	},
	pixelRatio: uni.getSystemInfoSync().pixelRatio
})


// ======= 计算属性 =======
// 总费用计算（总油费+总养车费用）
const totalCosts = computed(() => {
  return Number(fuelData.value.fuelTotalCosts || 0) + Number(fuelData.value.expenseTotalCosts || 0)
})

// 车辆切换菜单选项（包含管理车辆选项）
const carMenuList = computed(() => {
	// 车辆选项
	const carActions = carList.value.map(v => ({
		name: v.name,
		carId: v.id,
		color: currentCar.value.id === v.id ? '#1890ff' : undefined
	}))

	// 添加管理车辆选项
	carActions.push({
		name: '管理车辆',
		color: '#ff4d4f',
		isManageOption: true
	})
	return carActions
})

// 油耗趋势 -> 图表数据
const chartData = computed(() => {
	return {
		categories: trendData.value.map(item => {
			// 格式化日期显示（年-月-日）
			if (item.date) {
				const date = new Date(item.date);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
			}
			return '';
		}),
		series: [{
			name: '油耗',
			data: trendData.value.map(item => item.fuelEconomy)
		}]
	}
})

// 养车分类数据饼图 -> 图表数据
const pieChartData = computed(() => {
	return {
		series: [{
			data: expenseData.value
		}]
	};
})


// ======= 车辆选择相关函数 =======
// 车辆选择处理
const carSelect = async (selected) => {
	// 判断是管理车辆选项还是切换车辆选项
	if (selected.isManageOption) {
		// 跳转到车辆管理页面
		uni.navigateTo({
			url: '/pages/car/car'
		})
	} else if (selected.carId) {
		// 切换车辆
		try {
			const carId = parseInt(selected.carId)
			const success = await carApi.setCurrentCar(carId)
			if (success) {
				await loadCarData()
				uni.$u.toast('车辆切换成功')
			} else {
				uni.$u.toast('车辆切换失败')
			}
		} catch (error) {
			uni.$u.toast('车辆切换失败')
			console.error('车辆切换失败:', error)
		}
	}
}


// ======= 年份筛选器相关函数 =======
// 初始化年份筛选器列数据（包含全部选项）
const initYearPicker = () => {
	// 生成近10年的年份选项
	const currentYear = new Date().getFullYear()
	const years = []
	for (let i = 0; i < 10; i++) {
		years.push(currentYear - i)
	}
	yearColumnsData.value = [
		['全部', ...years]
	]
}

// 打开年份筛选器
const openYearPicker = (module) => {
	yearPickerShow.value[module] = true
}

// 年份筛选器取消处理
const handleYearCancel = (module = 'trendModule') => {
	yearPickerShow.value[module] = false
}

// 年份筛选器确认处理
const handleYearConfirm = async (e, module = 'trendModule') => {
	yearSelection.value[module] = e.value[0]
	await loadStatsData()
	yearPickerShow.value[module] = false
}


// ======= 数据加载相关函数 =======
// 加载车辆数据
const loadCarData = async () => {
	try {
		// 获取当前车辆和车辆列表
		const [currentCarResult, carListResult] = await Promise.all([
			carApi.getCurrentCar(),
			carApi.getCarList()
		])

		currentCar.value = currentCarResult
		carList.value = carListResult

		// 如果有选中的车辆，加载相关数据
		if (currentCar.value && currentCar.value.id) {
			await loadStatsData()
		}
	} catch (error) {
		uni.$u.toast('加载车辆数据失败')
		console.error('加载车辆数据失败:', error)
	}
}

// 加载油价数据
const loadOilPrice = async () => {
	try {
		// 获取当前油价和下一次更新时间
		const oilPriceResult = await getCurrentOilPriceWithNextUpdate()
		oilPriceInfo.value = oilPriceResult
	} catch (error) {
		uni.$u.toast('加载油价数据失败')
		console.error('加载油价数据失败:', error)
	}
}

// 加载用车统计数据和油耗趋势数据
const loadStatsData = async () => {
	if (!currentCar.value || !currentCar.value.id) {
		return
	}

	try {
		const [fuelDataResult, trendDataResult, expenseDataResult] = await Promise.all([
			homeApi.getFuelData(currentCar.value.id, yearSelection.value.fuelModule),
			homeApi.getTrendData(currentCar.value.id, yearSelection.value.trendModule),
			homeApi.getExpenseData(currentCar.value.id, yearSelection.value.expenseModule)
		])

		fuelData.value = fuelDataResult
		trendData.value = trendDataResult
		expenseData.value = expenseDataResult
	} catch (error) {
		uni.$u.toast('加载数据失败')
		console.error('加载数据失败:', error)
	}
}

// 悬浮按钮点击处理（添加加油记录/养车记录）
const floatButtonClick = (event) => {
	const index = event.index
	switch (index) {
		case 0:
			uni.navigateTo({
				url: '/pages/fuel/form?carId=' + currentCar.value.id
			})
			break
		case 1:
			uni.navigateTo({
				url: '/pages/expense/form?carId=' + currentCar.value.id
			})
			break
	}
}

// ======= 初始化应用 =======
const initApp = async () => {
	const app = getApp();
	await app.waitForDBReady();
	console.log('加载首页数据...');
	// 加载油价数据
	await loadOilPrice()
	// 初始化年份选择器
	initYearPicker()
	// 加载车辆数据
	await loadCarData()
}

onMounted(async () => {
	await initApp();
});

onShow(async () => {
	await initApp();
})
</script>

<style lang="scss" scoped>
/* 容器样式 */
.container {
	padding: 20rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 车辆选择 */
.car-container {
	background: #fff;
	border-radius: 12rpx;
	padding: 20rpx 30rpx;
	margin-bottom: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 左侧车辆信息 */
.car-info-left {
	display: flex;
	align-items: center;
	flex: 1;
	min-width: 0;
	height: 100%;
}

.car-name {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-left: 20rpx;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.arrow-icon {
	transform: rotate(-90deg);
}

/* 右侧油价信息 */
.oil-info-right {
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 4rpx;
	min-width: 120rpx;
}

.oil-price {
	font-size: 22rpx;
	font-weight: 500;
	color: #fa8c16;
}

.update-date {
	font-size: 22rpx;
	font-weight: 500;
	color: #52c41a;
}

/* 总费用样式 */
.total-costs {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-left: 10rpx;
}

/* 用车统计 */
.fuel-module-container {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.fuel-module-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.fuel-module-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.fuel-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20rpx;
}

.fuel-card {
	border-radius: 8rpx;
	padding: 20rpx 10rpx;
	text-align: center;
}

.fuel-title {
	display: block;
	font-size: 28rpx;
	color: #868686;
	margin-bottom: 10rpx;
}

.fuel-value {
	display: block;
	font-size: 40rpx;
	font-weight: bold;
	color: #1890ff;
	margin-bottom: 10rpx;
}

.fuel-unit {
	display: block;
	font-size: 24rpx;
	color: #999;
}

/* 油耗趋势 */
.trend-module-container {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx 20rpx 20rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 养车分类数据分布 */
.expense-module-container {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx 20rpx 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.expense-module-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.expense-module-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
}

.trend-module-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.trend-module-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	flex: 1;
}

/* 年份选择器 */
.year-picker-wrapper {
	padding: 8rpx 16rpx;
	background: #f5f5f5;
	border-radius: 8rpx;
	font-size: 24rpx;
	white-space: nowrap;
}
</style>